package com.juku2024.juku

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.SearchView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.juku2024.juku.adapter.VideoListAdapter
import com.juku2024.juku.base.BaseActivity
import com.juku2024.juku.callback.OnSearchKeySelectedListener
import com.juku2024.juku.model.CategorySearchModel
import com.juku2024.juku.model.CategorySearchResultModel
import com.juku2024.juku.model.CategorySearchTagModel
import com.juku2024.juku.model.Genre
import com.juku2024.juku.network.retrofit.OnRetrofitResultListener
import com.juku2024.juku.tools.AppUtils
import com.juku2024.juku.tools.Constants
import com.juku2024.juku.tools.LogC
import com.juku2024.juku.tools.WrapGridLayoutManager
import com.juku2024.juku.viewmodel.VideoListViewModel
import com.google.android.material.appbar.AppBarLayout
import com.juku2024.juku.widget.CategorySearchKeyView
import com.juku2024.juku.widget.HeaderView
import com.juku2024.juku.widget.LoadingView
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.abs

class VideoListActivity : BaseActivity() {

    companion object {
        fun toCategory(context: Context, genre: Genre) {
            val intent = Intent(context, VideoListActivity::class.java)
            intent.putExtra(Constants.AROUTER_KEY_GENRE, genre)
            context.startActivity(intent)
        }

        const val CATEGORY_CATEGORY = 1
        const val CATEGORY_YEAR = 2
    }

    private var page: Int = 1
    private var startTime = 0L
    private var count: Int = 0
    private var yearID: Int = 0
    private var genreId: Int = 2
    private var featureID: Int = 0
    private val searchTag = "%s·%s"
    private var yearKeyWord: String? = null
    private var categoryKeyWord: String? = null
    private val adapter by lazy { VideoListAdapter(ArrayList()) }
    private var categoryList: ArrayList<CategorySearchTagModel>? = null
    private val viewModel by lazy { getViewModel(VideoListViewModel::class.java) }

    private lateinit var header: HeaderView
    private lateinit var tvTopTitle: TextView
    private lateinit var appBarLayout: AppBarLayout
    private lateinit var categoryRecycler: RecyclerView
    private lateinit var categoryLoadingView: LoadingView
    private lateinit var searchKeyView: CategorySearchKeyView

    override fun getLayoutResId(): Int {
        return R.layout.activity_category
    }

    override fun initView() {
        super.initView()
        header = findViewById(R.id.header)
        tvTopTitle = findViewById(R.id.tvTopTitle)
        appBarLayout = findViewById(R.id.appBarLayout)
        searchKeyView = findViewById(R.id.searchKeyView)
        categoryRecycler = findViewById(R.id.categoryRecycler)
        categoryLoadingView = findViewById(R.id.categoryLoadingView)

        val gridLayoutManager = WrapGridLayoutManager(this, 3)
        gridLayoutManager.spanSizeLookup =
            object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(pos: Int): Int {
                    return if (pos == adapter.data.size) {
                        3
                    } else {
                        1
                    }
                }
            }
        categoryRecycler.layoutManager = gridLayoutManager
        categoryRecycler.adapter = adapter
    }
    @Suppress("DEPRECATION")
    @Deprecated("Deprecated in Java")
    override fun init(savedInstanceState: Bundle?) {
        val genre = intent?.getParcelableExtra(Constants.AROUTER_KEY_GENRE) as Genre?
        if (genre == null) {
            categoryLoadingView.showEmptyStatus(getString(R.string.category_list_empty))
            return
        }
        header.setTitle(genre.name)

        genreId = genre.genre_id
        if (genreId < 0) {
            categoryLoadingView.hideLoading()
            categoryLoadingView.showEmptyStatus(getString(R.string.category_list_empty))
            return
        }
    }

    override fun bindEvent() {
        super.bindEvent()
        adapter.setOnItemClickListener { _, _, position ->
            VideoDetailActivity.toVideoDetail(this, adapter.data[position].id, adapter.data[position].name)
        }

        appBarLayout.addOnOffsetChangedListener { appBarLayout, height ->
            val appBarMeasuredHeight = appBarLayout?.measuredHeight ?: 0
            tvTopTitle.alpha = abs(height) / (appBarMeasuredHeight * 1.0f)
            if (height < 0) {
                tvTopTitle.isClickable = true
                tvTopTitle.visibility = View.VISIBLE
            } else {
                tvTopTitle.isClickable = false
                tvTopTitle.visibility = View.GONE
            }
        }

        searchKeyView.onSearchKeySelected = object : OnSearchKeySelectedListener {
            override fun onSearchKeySelected(
                keyId: Int,
                classes: Int,
                keyModel: CategorySearchTagModel.CategorySearchItemModel
            ) {
                categoryLoadingView.showLoading()
                // 设置顶部的搜索字段
                setTopSearchKey(classes, keyId, keyModel.name)
                /**
                 * 清空数据，数据变化后立刻通知adapter
                 */
                adapter.data.clear()
                adapter.notifyDataSetChanged()
                page = 1
                count = 0
                // 每次搜索都清空列表
                doHttpGetSearchResult()
            }
        }

        adapter.loadMoreModule.setOnLoadMoreListener {
            LogC.e("LoadMore -> count=${count}, adapterSize -> ${adapter.data.size}")
            if (count <= adapter.data.size) { // 全部请求完成
                adapter.loadMoreModule.loadMoreEnd()
                return@setOnLoadMoreListener
            }
            LogC.d("onLoadMore.....")
            doHttpGetSearchResult()
        }

        tvTopTitle.setOnClickListener {
            categoryRecycler.smoothScrollToPosition(0)
        }
    }

    override fun onResume() {
        super.onResume()
        startTime = System.currentTimeMillis()
        // 继续请求列表
        categoryLoadingView.showLoading()
        if (adapter.data.isEmpty()) {
            // 设置初始的文案
            categoryKeyWord = getString(R.string.category_all)
            // 年费默认最新
            val calendar = Calendar.getInstance()
            calendar.time = Date()
            yearKeyWord = calendar.get(Calendar.YEAR).toString()
            adapter.category = genreId

            doHttpSearchTag()
        } else {
            displayUI()
        }
    }


    /**
     * 获取顶部搜索关键字列表
     */
    private fun doHttpSearchTag() {
        // 还原数据
        categoryList?.clear()
        viewModel.getSearchTagList(genreId, object : OnRetrofitResultListener<CategorySearchModel> {
            override fun onSuccess(t: CategorySearchModel) {
                if (isActivityNotActive()) return
                // 追加"全部"tag
                for (i in t.data.indices) {
                    val categoryBean = t.data[i]
                    val data = categoryBean.data
                    val item = CategorySearchTagModel.CategorySearchItemModel()
                    item.id = 0
                    // name="全部"
                    item.name = categoryBean.name
                    data.add(0, item)
                }
                // 获取当前最新年份的yearId
                val yearSearchModel = t.data.filter { searchModel ->
                    searchModel.classes == CATEGORY_YEAR
                }.firstOrNull()

                yearID = if (yearSearchModel?.data.isNullOrEmpty()) {
                    0
                } else {
                    yearSearchModel?.data?.filterIndexed { index, categorySearchModel ->
                        val isFind = categorySearchModel.name == yearKeyWord
                        if (isFind) {
                            yearSearchModel.checkedPos = index
                        }
                        return@filterIndexed isFind
                    }?.firstOrNull()?.id ?: 0
                }
                categoryList = t.data
                initSearchTag()
                // 根据searchTag，搜索对应的内容
                // 还原数据
                adapter.data.clear()
                adapter.notifyDataSetChanged()
                page = 1
                count = 0
                doHttpGetSearchResult()
            }

            override fun onFailed(msg: String) {
                showSearchTagError()
            }
        })
    }

    private fun initSearchTag() {
        categoryList?.apply {
            // 设置搜索文本
            setTopSearchKey(CATEGORY_YEAR, yearID, yearKeyWord!!)
            // 显示
            searchKeyView.visibility = View.VISIBLE
            searchKeyView.init(this)
        }
    }

    /**
     * 获取搜索关键字对应的列表
     */
    private fun doHttpGetSearchResult() {
        viewModel.getCategoryList(
            genreId = genreId,
            feature = featureID,
            year = yearID,
            page = page,
            callback = object : OnRetrofitResultListener<CategorySearchResultModel> {
                override fun onSuccess(t: CategorySearchResultModel) {
                    if (isActivityNotActive()) return
                    if (t.album?.results?.isEmpty() == true) {
                        categoryLoadingView.hideLoading()
                        if (adapter.data.isEmpty()) {
                            categoryLoadingView.showEmptyStatus(getString(R.string.category_list_empty))
                            adapter.loadMoreModule.loadMoreEnd(true)
                        } else {
                            adapter.loadMoreModule.loadMoreFail()
                        }
                        return
                    }
                    // 请求到一次数据，页数都会自增
                    page++
                    count = t.album.count

                    if (adapter.data.isEmpty()) {
                        adapter.setList(t.album.results)
                    } else {
                        adapter.addData(t.album.results)
                    }

                    if (adapter.data.size < count) {
                        adapter.loadMoreModule.loadMoreComplete()
                    } else {
                        adapter.loadMoreModule.loadMoreEnd()
                    }
                    categoryRecycler.visibility = View.VISIBLE
                    categoryLoadingView.hideLoading()
                }

                override fun onFailed(msg: String) {
                    if (isActivityNotActive()) return
                    categoryLoadingView.hideLoading()
                    if (adapter.data.isEmpty()) {
                        categoryLoadingView.showEmptyStatus(getString(R.string.category_list_empty))
                    } else {
                        adapter.loadMoreModule.loadMoreFail()
                    }
                }
            })
    }


    private fun displayUI() {
        searchKeyView.postDelayed({
            if (isActivityNotActive()) {
                return@postDelayed
            }
            categoryLoadingView.hideLoading()
            // 设置搜索文本
            setTopSearchKey(CATEGORY_YEAR, yearID, yearKeyWord!!)
            // 显示
            searchKeyView.visibility = View.VISIBLE
            searchKeyView.init(categoryList)
            categoryRecycler.visibility = View.VISIBLE
            // 设置下滑的顶部字段
            tvTopTitle.visibility = View.VISIBLE
            tvTopTitle.text = String.format(searchTag, categoryKeyWord, yearKeyWord)
        }, 150)

    }


    private fun setTopSearchKey(
        classes: Int,
        keyId: Int,
        keyValue: String
    ) {
        if (classes == CATEGORY_CATEGORY) {
            categoryKeyWord = if (keyId != 0) {
                keyValue
            } else {
                getString(R.string.category_all)
            }
            featureID = keyId
            //选择的是feature
        } else if (classes == CATEGORY_YEAR) {
            yearKeyWord = if (keyId != 0) {
                keyValue
            } else {
                getString(R.string.year_all)
            }
            yearID = keyId
            //选择的是year
        }
        tvTopTitle.text = String.format(searchTag, categoryKeyWord, yearKeyWord)
    }


    private fun showSearchTagError() {
        if (isActivityNotActive()) return
        categoryLoadingView.hideLoading()
        showErrorDialog(
            AppUtils.getString(R.string.fetch_category_error),
            AppUtils.getString(R.string.retry),
            {
                hideErrorDialog()
                categoryLoadingView.showLoading()
                categoryLoadingView.postDelayed({
                    doHttpSearchTag()
                }, 1000)
            },
            AppUtils.getString(R.string.cancel),
            {
                hideErrorDialog()
            })
    }

}